<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

class DrawCash extends \Service\Common\BaseModel
{
    protected $name = 'draw_cash';

    const STATUS_SUBMIT = 0;//已提交
    const STATUS_PAID = 1;//已发放
    const STATUS_REJECT = 2;//已驳回
    const STATUS_PAID2 = 3;//已审核,发放前操作

    //审核提现
    public function checkDrawMoney($draw_cash_id, $status, $remark)
    {
        $result = $this->find($draw_cash_id);
        if (!$result) {
            throw new \Exception("无效的记录");
        }

        
        if (in_array($result['status'], [self::STATUS_PAID,self::STATUS_REJECT])){
        	throw new \Exception("已发放或已驳回，请不要重复操作");
        }

        if ($status == self::STATUS_SUBMIT) {
            return true;
        }

        if (!in_array($status, [self::STATUS_PAID, self::STATUS_REJECT, self::STATUS_PAID2])) {
            throw new \Exception("无效的操作");
        }

        try {
            $this->startTrans();
            //更新提现状态
            $update = $this->save([
                'id' => $result['id'],
                'status' => $status,
                'remark' => $remark,
                'update_time' => date('Y-m-d H:i:s'),
            ]);
            if ($update === false) {
                throw new \Exception("更新提现状态失败");
            }
            //资金记录
            switch ($status) {
                case self::STATUS_PAID://已放款
                    OE('user')->drawMoneySuccess($result['uid'], $result['draw_money'], $result['id']);
                    break;
                case self::STATUS_REJECT://驳回
                    OE('user')->unfreezeDrawMoney($result['uid'], $result['draw_money'], $result['id']);
                    break;
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }

    //申请提现
    public function apply($data, $uid, $login_info)
    {
        //验证支付密码
        OE('user')->checkpaypassword($uid, $data['pay_password']);

        //最小金额
        $draw_min_money = C('DRAW_MIN_MONEY', null, 0.01);
        if ($data['draw_money'] < $draw_min_money) {
            throw new \Exception("提现最小金额不符,最小为{$draw_min_money}元");
        }

        //最小面额
        $draw_money_multiple = C('DRAW_MONEY_MULTIPLE', null, 0);
        if (!($draw_money_multiple && ($data['draw_money'] % $draw_min_money === 0))) {
            throw new \Exception("提现面额倍数不符，应为{$draw_money_multiple}的整数倍");
        }

        //提现日期
        $draw_money_day = C('DRAW_MONEY_DAY');
        $day = date("w") == 0 ? 7 : date("w");
        $draw_money_day = array_filter(explode(',', trim($draw_money_day)));
        if ($draw_money_day && !in_array($day, $draw_money_day)) {
            throw new \Exception("今日不可提现");
        }

        //提现时间
        $draw_money_time = C('DRAW_MONEY_TIME');
        $draw_money_time = array_filter(explode(',', trim($draw_money_time)));
        if ($draw_money_time) {
            list($start, $end) = $draw_money_time;
            $today = date('Y-m-d');
            if (!(time() >= strtotime("$today $start") && time() <= strtotime("$today $end"))) {
                throw new \Exception("已过可提现时间");
            }
        }

        //是否邦卡
        if (!$login_info['bank_no']) {
            throw new \Exception("没有绑定银行卡");
        }

        //余额
        if ($data['draw_money'] > $login_info['balance']) {
            throw new \exception("余额不足");
        }

        try {
            $this->startTrans();
            //提现记录
            $draw_money_fee = C('DRAW_MONEY_FEE', null, 0);
            $fee_money = get_decimal($data['draw_money'] * $draw_money_fee);
            $insert_id = $this->add([
                'create_time' => date('Y-m-d H:i:s'),
                'draw_money' => $data['draw_money'],//提现金额
                'pay_money' => $data['draw_money'] - $fee_money,//发放金额
                'fee_money' => $fee_money,//手续费金额
                'fee_money_percent' => $draw_money_fee,//手续费比例
                'uid' => $uid,
                'bank_type' => $login_info['bank_type_label'],
                'bank_no' => $login_info['bank_no'],
                'real_name' => $login_info['real_name'],
            ]);
            if (!$insert_id) {
                throw new \Exception("提现记录插入失败");
            }
            //资金记录
            OE('user')->drawMoney($uid, $data['draw_money'], $insert_id);
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }

        return true;
    }

    //列表
    public function drawList($uid, $status, $page_num = 1, $page_size = 5)
    {
        $where = [
            'uid' => $uid,
            'status' => $status
        ];
        $list = (array)$this->where($where)->order('id desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
            $total_draw_money = get_decimal($this->where(['uid' => $uid])->sum('pay_money'))
        ];
    }
}